package filters

import (
	"comment/models"
	"regexp"

	"github.com/astaxie/beego/context"
)

func LoginInfo(ctx *context.Context) models.User {
	session := ctx.Input.Session("userId")
	var user models.User
	if id, ok := session.(int); ok {
		user = models.FindUserById(id)
	}
	return user
}

//权限
var HasPermission = func(ctx *context.Context) {
	session := ctx.Input.Session("userId")
	url := ctx.Request.RequestURI
	b, _ := regexp.MatchString("/api/*", url)
	if session == nil && url != "/logout" && url != "/login" && !b {
		ctx.Redirect(302, "/login")
	} else {
		var permissions []*models.Permission
		if id, ok := session.(int); ok {
			permissions = models.FindPermissionByUser(id)
		}
		var flag = false
		b, _ := regexp.MatchString("/api/*", url)
		if url == "/" || url == "/login" || url == "/logout" || b {
			flag = true
		} else {
			for _, v := range permissions {
				if v.Url != "" {
					//包含
					if a, _ := regexp.MatchString(v.Url, url); a {
						flag = true
						break
					}
				}

			}
		}
		if !flag {
			ctx.WriteString("你没有权限访问这个页面")
		} else {
			ctx.Input.SetData("userId", session)
			ctx.Input.SetData("menu", permissions)
			ctx.Input.SetData("user", ctx.Input.Session("User"))
			ctx.Input.SetData("role", ctx.Input.Session("Role"))
		}
	}
}
